package com.ruoyi.web.controller.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.OrderStatus;
import com.ruoyi.common.enums.PayType;
import com.ruoyi.common.enums.WxPayState;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.GwPlatformServiceOrder;
import com.ruoyi.system.mapper.GwPlatformServiceOrderMapper;
import com.ruoyi.system.service.IGwPlatformRightsOrderService;
import com.ruoyi.system.service.IGwPlatformServiceOrderService;
import com.ruoyi.system.utils.AlipayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @ProjectName: back
 * @Package: com.ruoyi.web.controller.pay
 * @ClassName: AlipayController
 * @Author: haiyue
 * @Description: 支付宝
 * @Date: 2025/6/9 下午 7:43:32
 * @Version: 1.0
 */
@RestController
@RequestMapping("/pay/alipay")
public class AlipayController {
    @Autowired
    private AlipayUtil alipayUtil;
    @Autowired
    private IGwPlatformRightsOrderService rightsOrderService;
    @Autowired
    private IGwPlatformServiceOrderService serviceOrderService;
    @Autowired
    private GwPlatformServiceOrderMapper serviceOrderMapper;
    /**
     * 生成支付页面
     */
    @GetMapping("/payPage")
    public void payPage(String outTradeNo, String subject, String totalAmount, String body,
                        HttpServletResponse response) throws Exception {
//        // 设置响应格式
        response.setContentType("text/html;charset=" + "utf-8");
//
//        // 生成支付页面
//        String form = alipayUtil.createPayPage(outTradeNo, subject, totalAmount, body);

        // 输出表单
//        PrintWriter out = response.getWriter();
//        out.println(form);
//        out.flush();
//        out.close();
    }

    /**
     * 支付宝同步回调
     */
    @PostMapping("/rights/returnUrl")
    public String rightsReturnUrl(HttpServletRequest request) {
        // 验证签名
        try {
            boolean signVerified = alipayUtil.verifySign(request);
            if (signVerified) {
                // 处理支付结果
                String outTradeNo = request.getParameter("out_trade_no");
                String tradeStatus = request.getParameter("trade_status");



                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    // 更新订单状态
//                    orderService.updateOrderStatus(outTradeNo, OrderStatus.PAID);

                    // 可以添加额外的参数，如订单号、支付结果等
                    return "redirect:b/platfromEquity";
                }
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "fail";
        }
        return "fail";
    }

    /**
     * 支付宝同步回调
     */
    @PostMapping("/service/returnUrl")
    public String serviceReturnUrl(@RequestParam(required = false) String redirect, HttpServletRequest request) {
        // 验证签名
        try {
            boolean signVerified = alipayUtil.verifySign(request);
            if (signVerified) {
                // 处理支付结果
                String outTradeNo = request.getParameter("out_trade_no");
                String tradeStatus = request.getParameter("trade_status");



                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    // 更新订单状态
//                    orderService.updateOrderStatus(outTradeNo, OrderStatus.PAID);

                    // 构建返回若依系统的URL
                    String redirectUrl = StringUtils.isNotBlank(redirect) ?
                            redirect : "/dashboard";

                    // 可以添加额外的参数，如订单号、支付结果等
                    return "redirect:" + redirectUrl + "?orderId=" + outTradeNo + "&status=success";
                }
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "fail";
        }

        // 这里可以获取支付宝同步返回的参数，如订单号、支付状态等
        String outTradeNo = request.getParameter("out_trade_no");
        String tradeNo = request.getParameter("trade_no");
        String totalAmount = request.getParameter("total_amount");

        // 根据业务需求处理返回结果
        return "支付成功页面";
    }

    /**
     * 支付宝异步回调
     */
    @GetMapping("/rights/notifyUrl")
    public void rightsNotifyUrl(HttpServletRequest request,HttpServletResponse response) {
        try {
            // 验证签名
            boolean signVerified = alipayUtil.verifySign(request);

            if (signVerified) {
                // 验证成功
                // 商户订单号
                String outTradeNo = request.getParameter("out_trade_no");
                // 支付宝交易号
                String tradeNo = request.getParameter("trade_no");

                String gmtPayment = request.getParameter("timestamp");

                rightsOrderService.handleRightsOrderByAlipay(outTradeNo,tradeNo,gmtPayment);

                // 请不要修改或删除
                response.sendRedirect("https://gowork365.com/b/platfromEquity");
            } else {
                // 验证失败
                response.sendRedirect("https://gowork365.com/b/platfromEquity");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝异步回调
     */
    @GetMapping("/service/notifyUrl")
    public void serviceNotifyUrl(HttpServletRequest request,HttpServletResponse response) {
        try {
            // 验证签名
            boolean signVerified = alipayUtil.verifySign(request);

            if (signVerified) {
                // 验证成功
                // 商户订单号
                String outTradeNo = request.getParameter("out_trade_no");
                // 支付宝交易号
                String tradeNo = request.getParameter("trade_no");
                // 支付时间
                String gmtPayment = request.getParameter("timestamp");

                GwPlatformServiceOrder serviceOrder = serviceOrderService.selectGwPlatformServiceOrderById(outTradeNo);
                serviceOrder.setPayType(PayType.ZHI_FU_BAO.getCode());
                serviceOrder.setPayTime(DateUtils.parseDate(gmtPayment));
                serviceOrder.setStatus(OrderStatus.PAY.getCode());
                serviceOrder.setTransactionId(tradeNo);
                serviceOrderMapper.updateGwPlatformServiceOrder(serviceOrder);

                // 请不要修改或删除
                response.sendRedirect("https://gowork365.com/b/myPlatformServiceOrder");
            } else {
                // 验证失败
                response.sendRedirect("https://gowork365.com/b/myPlatformServiceOrder");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询订单状态
     */
    @GetMapping("/queryOrder")
    public AjaxResult queryOrder(String outTradeNo, String tradeNo) {
//        try {
//            AlipayTradeQueryResponse response = alipayUtil.queryOrder(outTradeNo, tradeNo);
//            if (response.isSuccess()) {
//                return AjaxResult.success("查询成功", response);
//            } else {
//                return AjaxResult.error("查询失败: " + response.getMsg());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error("查询异常: " + e.getMessage());
//        }
        return AjaxResult.success();
    }

    /**
     * 订单退款
     */
    @PostMapping("/refundOrder")
    public AjaxResult refundOrder(String outTradeNo, String tradeNo, String refundAmount, String refundReason) {
//        try {
//            if (StringUtils.isEmpty(refundReason)) {
//                refundReason = "用户申请退款";
//            }
//
//            AlipayTradeRefundResponse response = alipayUtil.refundOrder(outTradeNo, tradeNo, refundAmount, refundReason);
//            if (response.isSuccess()) {
//                return AjaxResult.success("退款成功", response);
//            } else {
//                return AjaxResult.error("退款失败: " + response.getMsg());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error("退款异常: " + e.getMessage());
//        }
        return AjaxResult.success();
    }
}
